#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import List, Dict, Any, Optional, Tuple, Literal
from datetime import datetime

from app.core.logging import get_logger, LoggerMixin
from app.core.exceptions import NotFoundError, DatabaseError
from app.repositories.query_history import QueryHistoryRepository
from app.models.database import QueryHistory

# 创建日志记录器
logger = get_logger("query_history_service")


class QueryHistoryService(LoggerMixin):
    """查询历史服务
    
    管理查询历史相关业务逻辑
    """
    
    def __init__(self, query_history_repo: QueryHistoryRepository):
        """初始化查询历史服务
        
        Args:
            query_history_repo: 查询历史仓库
        """
        self.query_history_repo = query_history_repo
    
    async def record_generation(
        self,
        project_id: str,
        question: str,
        generated_sql: str,
        db_type: str = "mysql"
    ) -> QueryHistory:
        """记录生成历史
        
        Args:
            project_id: 项目ID
            question: 问题
            generated_sql: 生成的SQL
            db_type: 数据库类型
            
        Returns:
            QueryHistory: 创建的查询历史
            
        Raises:
            DatabaseError: 当创建失败时
        """
        try:
            query_history = await self.query_history_repo.create(
                project_id=project_id,
                history_type="generation",
                question=question,
                generated_sql=generated_sql,
                db_type=db_type
            )
            
            self.logger.info(f"已记录生成历史: {query_history.id}")
            return query_history
            
        except Exception as e:
            self.logger.error(f"记录生成历史失败: {str(e)}")
            raise
    
    async def record_correction(
        self,
        project_id: str,
        question: str,
        error_sql: str,
        error_message: str,
        corrected_sql: str,
        db_type: str = "mysql"
    ) -> QueryHistory:
        """记录纠错历史
        
        Args:
            project_id: 项目ID
            question: 问题
            error_sql: 错误的SQL
            error_message: 错误信息
            corrected_sql: 纠正后的SQL
            db_type: 数据库类型
            
        Returns:
            QueryHistory: 创建的查询历史
            
        Raises:
            DatabaseError: 当创建失败时
        """
        try:
            query_history = await self.query_history_repo.create(
                project_id=project_id,
                history_type="correction",
                question=question,
                generated_sql=corrected_sql,
                error_sql=error_sql,
                error_message=error_message,
                db_type=db_type
            )
            
            self.logger.info(f"已记录纠错历史: {query_history.id}")
            return query_history
            
        except Exception as e:
            self.logger.error(f"记录纠错历史失败: {str(e)}")
            raise
    
    async def get_history(self, history_id: int) -> QueryHistory:
        """获取查询历史
        
        Args:
            history_id: 查询历史ID
            
        Returns:
            QueryHistory: 查询历史
            
        Raises:
            NotFoundError: 当查询历史不存在时
        """
        try:
            query_history = await self.query_history_repo.get_by_id(history_id)
            return query_history
        except Exception as e:
            self.logger.error(f"获取查询历史失败: {str(e)}")
            raise
    
    async def list_history(
        self,
        project_id: str,
        history_type: Optional[str] = None,
        start_date: Optional[datetime] = None,
        end_date: Optional[datetime] = None,
        db_type: Optional[str] = None,
        limit: int = 10,
        offset: int = 0
    ) -> Tuple[List[QueryHistory], int]:
        """列出查询历史
        
        Args:
            project_id: 项目ID
            history_type: 历史类型
            start_date: 开始日期
            end_date: 结束日期
            db_type: 数据库类型
            limit: 限制数量
            offset: 偏移量
            
        Returns:
            Tuple[List[QueryHistory], int]: 查询历史列表和总数
            
        Raises:
            DatabaseError: 当查询失败时
        """
        try:
            query_history_list, total = await self.query_history_repo.list_by_project(
                project_id=project_id,
                history_type=history_type,
                start_date=start_date,
                end_date=end_date,
                db_type=db_type,
                limit=limit,
                offset=offset
            )
            return query_history_list, total
        except Exception as e:
            self.logger.error(f"列出查询历史失败: {str(e)}")
            raise
    
    async def find_similar_questions(
        self,
        project_id: str,
        question: str,
        limit: int = 5
    ) -> List[QueryHistory]:
        """查找相似问题的历史记录
        
        Args:
            project_id: 项目ID
            question: 问题
            limit: 限制数量
            
        Returns:
            List[QueryHistory]: 查询历史列表
            
        Raises:
            DatabaseError: 当查询失败时
        """
        try:
            # 简单的文本匹配
            query_history_list = await self.query_history_repo.search_by_question(
                project_id=project_id,
                query=question,
                limit=limit
            )
            return query_history_list
        except Exception as e:
            self.logger.error(f"查找相似问题失败: {str(e)}")
            raise